#include <REGX52.H>
#include "Key.h"
#include "LCD1602.h"
#include "AT24C02.h"
#include "Delay.h"

unsigned char keyNum;
unsigned int num;

void main()
{
    LCD_Init();
//    LCD_ShowString(1, 1, "Hello");
//    AT24C02_writebyte(0, 147);
//    Delay(5);
//    AT24C02_writebyte(1, 147);
//    Delay(5);
//    AT24C02_writebyte(2, 147);
//    // 注意写周期，不能立即读出
//    Delay(5);
//    Data = AT24C02_readbyte(1);
//    LCD_ShowNum(2, 1, Data, 3);
    LCD_ShowNum(1, 1, num, 5);
	while (1)
    {
        keyNum = Key();
        if (keyNum == 1)
        {
            num++;
            LCD_ShowNum(1, 1, num, 5);
        }
        if (keyNum == 2)
        {
            num--;
            LCD_ShowNum(1, 1, num, 5);
        }
        if (keyNum == 3)
        {
            AT24C02_writebyte(0, num % 256);  // 写入低8位
            Delay(5);
            AT24C02_writebyte(0, num / 256);  // 写入高8位
            Delay(5);
            LCD_ShowString(2, 1, "Write Success");
            Delay(1000); 
            LCD_ShowString(2, 1, "             ");
        }
        if (keyNum == 4)
        {
            num = AT24C02_readbyte(0);  // 读出低8位数据
            num |= (AT24C02_readbyte(1) << 8);  // 再读出高8位数据，合成整个num
            LCD_ShowNum(1, 1, num, 5);
            LCD_ShowString(2, 1, "Read Success");
            Delay(1000);
            LCD_ShowString(2, 1, "            ");
        }
    }
}